package cn.jorian.framework.controller;

import cn.jorian.framework.bean.*;
import cn.jorian.framework.entity.User;
import cn.jorian.framework.service.ICheckService;
import cn.jorian.framework.service.ISongService;
import cn.jorian.framework.service.UserService;
import cn.jorian.framework.util.GsonUtil;
import com.alibaba.druid.filter.config.ConfigTools;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.reflect.TypeToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/test")
@Api(tags = "测试控制器")
public class TestController {

    @Autowired
    private UserService userService;

    @Autowired
    private ICheckService iCheckService;

    @Autowired
    private ISongService iSongService;

    @ApiOperation("获取列表")
    @PreAuthorize("hasAuthority('test')")
    @GetMapping("/getList")
    public ResponseResult<List<User>> getList() {
        ResponseResult<List<User>> result = new ResponseResult<>();
        result.setCode("200");
        result.setMessage("成功");
        result.setData(userService.list());
        return result;
    }

    @ApiOperation("获取列表带有分页")
    @GetMapping("/getListPage")
    public ResponseResult<IPage<User>> getListPage(@RequestParam("json") String json) {
        System.out.println("json:" + json);
        return userService.getListPage(json);
    }

    @ApiOperation("新增用户")
    @PreAuthorize("hasAuthority('add')")
    @PostMapping("/insert")
    public String insert(@RequestBody User user) {
       boolean result = userService.save(user);
       return result ? "成功" : "失败";
    }


    @ApiOperation("解密")
    @GetMapping("/desc")
    public String desc() throws Exception {
        String encryptedPassword = "dtLtHIvpwsYFrpxhF1XunOXll4UGHwuN0ffeMhwHEa81hp1Qv+lE4NpN4AmuZLYNgQhkRP+chaZm439tEMD21Q=="; // 替换为实际加密的密码
        String passwordKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALUsl9d4wovH47ix4sCm89yOAca60taKju+fXE13dZ3Q3rrLECa37g4gNRnJLioen4xs6yZvaR5C9wKVx40pXWUCAwEAAQ=="; // 替换为实际的密钥

        String decryptedPassword = ConfigTools.decrypt(passwordKey, encryptedPassword);
        System.out.println("Decrypted Password: " + decryptedPassword);
        return decryptedPassword;
    }

    @ApiOperation("商品下发")
    @PostMapping("/goods")
    public ResponseResult<GoodsBean> goods(@RequestParam("appkey") String appkey,
                                           @RequestParam("timestamp") String timestamp,
                                           @RequestParam("sign") String sign,
                                           @RequestParam("ver") String ver,
                                           @RequestParam("data") String data) {


        ApiRequestParam requestParam = new ApiRequestParam();
        requestParam.setAppkey(appkey);
        requestParam.setTimestamp(timestamp);
        requestParam.setSign(sign);
        requestParam.setVer(ver);
        requestParam.setData(data);

        System.out.println("param:" + GsonUtil.toJson(requestParam));

        return iCheckService.checkLegal(requestParam);
    }

    @ApiOperation("入库反馈")
    @PostMapping("/indoc_back")
    public ResponseResult indocBack(@RequestParam("appkey") String appkey,
                                    @RequestParam("timestamp") String timestamp,
                                    @RequestParam("sign") String sign,
                                    @RequestParam("ver") String ver,
                                    @RequestParam("data") String data) {


        ApiRequestParam requestParam = new ApiRequestParam();
        requestParam.setAppkey(appkey);
        requestParam.setTimestamp(timestamp);
        requestParam.setSign(sign);
        requestParam.setVer(ver);
        requestParam.setData(data);

        System.out.println("param:" + GsonUtil.toJson(requestParam));

        return iCheckService.checkLegal(requestParam);
    }


    @ApiOperation("测试elastic serach")
    @GetMapping("/findByName")
    public ResponseResult<List<SongBean>> findByName() {
        ResponseResult<List<SongBean>> responseResult = new ResponseResult<>();
        responseResult.setData(iSongService.findByName("妙手空空"));
        return responseResult;
    }

    @ApiOperation("测试elastic serach")
    @GetMapping("/save")
    public ResponseResult<SongBean> save() {
        ResponseResult<SongBean> responseResult = new ResponseResult<>();
        SongBean songBean = new SongBean();
        songBean.setName("妙手空空");
        songBean.setNote("十二生肖预告主题曲");
        songBean.setSinger("成龙/周华健/张震岳");
        responseResult.setData(iSongService.save(songBean));
        return responseResult;
    }


//    @ApiOperation("事务控制")
//    @PostMapping("/insertio")
//    public ResponseResult insert() {
//
//        DataSourceTransactionManager manager = new DataSourceTransactionManager();
//        manager.setDataSource(dataSource);
//
//        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
//        //设置超时  默认是5秒
//        def.setTimeout(3000);
//        //3.设置事务隔离级别，开启新事务
//        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
//        //4.获得事务状态，相当于开启事物
//        TransactionStatus status = manager.getTransaction(def);
//
//        for (int j = 0; j <= 3; j++) {
//            System.out.println(j);
//            Map<String, Object> map = org.elasticsearch.core.Map.of("stcompanyid", 83805, "goodsid",139573, "inbatchid", 238651075, "lotid", 2000702828);
//
//            QueryWrapper<Qtyrem> qtyremQueryWrapper = new QueryWrapper<>();
//            qtyremQueryWrapper.allEq(map);
//            List<Qtyrem> qtyremList = qtyremService.list(qtyremQueryWrapper);
//
//            QueryWrapper<Iotmp> iotmpQueryWrapper = new QueryWrapper<>();
//            iotmpQueryWrapper.allEq(map);
//            List<Iotmp> iotmpList = iotmpService.list(iotmpQueryWrapper);
//
//            if (qtyremList.isEmpty()) {
//                manager.rollback(status);
//                return ResponseResult.fail("没有库存");
//            }
//
//            Qtyrem qtyrem = qtyremList.get(0);
//            BigDecimal qty = qtyrem.getQty();
//
//            if (iotmpList.isEmpty()) {
//                boolean result = insertIo();
//                if (!result) {
//                    manager.rollback(status);
//                    return ResponseResult.fail("插入失败");
//                }
//            }
//            if (!iotmpList.isEmpty()) {
//                Iotmp iotmp = iotmpList.get(0);
//                BigDecimal ioQty = iotmp.getQty();
//
//                if (ioQty.doubleValue() >= qty.doubleValue()) {
//                    manager.rollback(status);
//                    return ResponseResult.fail("库存不足");
//                }
//                boolean result = insertIo();
//                if (!result) {
//                    manager.rollback(status);
//                    return ResponseResult.fail("插入失败");
//                }
//            }
//        }
//        manager.commit(status);
//        return ResponseResult.success();
//    }

    /**
     * 生成io
     * @return
     */
//    public boolean insertIo() {
//        Iotmp iotmp = new Iotmp();
//        iotmp.setStcompanyid(83805);
//        iotmp.setGoodsid(139573);
//        iotmp.setInbatchid(238651075);
//        iotmp.setLotid(2000702828);
//        iotmp.setQty(BigDecimal.valueOf(7.0));
//        return iotmpService.save(iotmp);
//    }

}
